function mle = SMLE_v2(params,data,random_draws,random_draws2,random_draws3,random_draws4, num_drugs, num_periods, id, outside, S)
%SMLE Computes likelihood function given data and parameter guess

    delta = params(1:3);
    
    alpha = params(4);
    gamma = params(5);
    mu1 = params(6);
    sigma1 = params(7);
    mu2 = params(8);
    sigma2 = params(9);
    mu3 = params(10);
    sigma3 = params(11);
    mu4 = params(12);
    sigma4 = params(13);
    
    random_draws = random_draws * sigma1 + mu1 + random_draws2 * sigma2 + mu2 +...
        random_draws3 * sigma3 + mu3 + random_draws4 * sigma4 + mu4;
    
    % STEP 1: transform data into ID, quarter u_ij based on parameters
    % Basic_part: drug quality - alpha * copay
    u = delta(data(:,3)) - ...
        alpha * data(:,5) + gamma * data(:,6);
    % repmat sideways and add random draw rows
    u = repmat(u,1,S) + random_draws(data(:,3) + num_drugs * (data(:,1) - 1), :);
    
    % STEP 2: aggregate and compute SMLE
    eu = exp(u);
    probs = zeros(size(outside,1),S);
    
    for i=1:S
        groupsum = 1 + accumarray(id, eu(:,i));
        eu_chosen = eu(:,i) .* data(:,4);
        chosen_sum = accumarray(id,eu_chosen);
        p = ((1 - outside) .* chosen_sum + outside * 1) ./ groupsum;
        
        probs(:,i) = p;
    end

    
    mean_probs= mean(probs,2);
    mle = sum(log(mean_probs));
end

